/*
 * @Author: zhousg
 * @Date: 2020-09-15 17:43:56
 * @Last Modified by: zhousg
 * @Last Modified time: 2020-11-11 10:19:08
 */

import request from '@/utils/request'
import message from '@/utils/message'
import confirm from '@/utils/confirm'
import clickoutside from '@/utils/clickoutside'
import loading from '@/utils/loading'
import store from '@/store'

// 导入xtx-开头的vue组件
const reqCom = require.context('../components', false, /^\.\/xtx-.*\.vue$/)

// 小兔鲜的扩展
export default {
  install (Vue) {
    // 批量注册全局组件
    reqCom.keys().forEach(key => {
      const component = reqCom(key).default
      Vue.component(component.name, component)
    })
    // 请求工具
    Vue.prototype.$http = request
    // 消息提示
    Vue.prototype.$message = message
    // 确认框
    Vue.prototype.$confirm = confirm
    // 休眠函数
    Vue.prototype.$sleep = (ms) => {
      return new Promise((resolve, reject) => {
        window.setTimeout(() => {
          resolve()
        }, ms)
      })
    }
    // 自定义指令
    // 元素外点击
    Vue.directive('clickoutside', clickoutside)
    // 加载层显示
    Vue.directive('loading', loading)
    // 校验登录
    Vue.mixin({
      methods: {
        checkLogin (cb) {
          const { token } = store.state.user
          if (token) {
            cb && cb()
          } else {
            this.$router.push({ path: '/login', query: { returnUrl: this.$route.fullPath } })
          }
        }
      }
    })
    // 手机号隐私
    Vue.filter('vagueMobile',
      (value) => {
        return value && value.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
    )
  }
}
